//
//  LoginViewController.m
//  Rabbit
//
//  Created by 阿帕 on 2018/11/14.
//  Copyright © 2018年 GCY. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "ForgetPasswordViewController.h"
#import "CYWebViewViewController.h"
#import "JPUSHService.h"
#import "ImageVerifyAlert.h"

@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *telTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UIButton *forgetPsdBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UIButton *agreementButton;
@property (weak, nonatomic) IBOutlet UIButton *isAgreeButton;
@property (weak, nonatomic) IBOutlet UIImageView *phoneImageView;
@property (weak, nonatomic) IBOutlet UIImageView *psdImageView;
@property (strong, nonatomic) IBOutlet UIButton *codeButton;

@end

@implementation LoginViewController

- (void)dealloc {
    [KNotificationCenter removeObserver:self name:@"LoginDismissEvent" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"登录";
    
    [KNotificationCenter addObserver:self selector:@selector(dismissClick) name:@"LoginDismissEvent" object:nil];
    [self setNavView];
    if (![DCSpeedy isBlankString:[UserDefaultUtil valueForKey:USER_PHONE]]) {
        self.passwordTextField.text = [UserDefaultUtil valueForKey:USER_PASSWORD];
        self.telTextField.text = [UserDefaultUtil valueForKey:USER_PHONE];
    }
    NSString *prefixStr = @"同意";
    NSString *agreementStr = [NSString stringWithFormat:@"《%@司机端隐私政策》", APP_PlatformName];
    
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:[prefixStr stringByAppendingString:agreementStr]];
    [attString addAttribute:(NSString*)NSForegroundColorAttributeName value:Light_TextColor range:[_agreementButton.titleLabel.text rangeOfString:prefixStr]];
    [attString addAttribute:(NSString*)NSForegroundColorAttributeName value:Theme_ColorValue range:[_agreementButton.titleLabel.text rangeOfString:agreementStr]];
    [_agreementButton setAttributedTitle:attString forState:UIControlStateNormal];
    
//    _phoneImageView.image = [[UIImage imageNamed:@"gcy_img_login_tel"] imageChangeColor:Theme_ColorValue];
//    _psdImageView.image = [[UIImage imageNamed:@"gcy_img_login_password"] imageChangeColor:Theme_ColorValue];
    
}

- (void)setNavView {
    
    _telTextField.textFieldType = CJTextFieldStringTypeNumber;
    _telTextField.maxLength = 11;
    
//    _passwordTextField.textFieldType = CJTextFieldStringTypePassword;
    _passwordTextField.maxLength = 18;
    
    _telTextField.textColor = Dark_TextColor;
    _passwordTextField.textColor = Dark_TextColor;
    [_loginButton setBackgroundColor:Theme_ColorValue];
    [_forgetPsdBtn setTitleColor:Theme_ColorValue forState:UIControlStateNormal];
    [_registerBtn setTitleColor:Theme_ColorValue forState:UIControlStateNormal];;
    cut(_loginButton, BTN_BORDER_RADIUS);
    
#ifdef DEBUG
    //@"17750000004"; @"13920130895";//
//    _telTextField.text =   @"13920130895"; //@"17666682734";
//    _passwordTextField.text = @"abcd1234";
#else

#endif
    
    //导航右按钮
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 30, 30);
    [rightBtn setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -10*SP_Width)];
    [rightBtn setImage:image(@"gcy_ptgd_icon_close") forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(dismissClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = right;
    
}

- (void)imgaeVerification {
    ImageVerifyAlert *imageVerifyAlert = [[ImageVerifyAlert alloc] initWithFrame:CGRectMake(0, 0, ScreenW-30, 210)];
    imageVerifyAlert.backgroundColor = [UIColor whiteColor];
    cut(imageVerifyAlert, 5);
    imageVerifyAlert.phoneNum = _telTextField.text;
    [[GlobalPopUpTool sharedInstance] popUpWithView:imageVerifyAlert withViewController:self withAnimation:YES withCanTapBgCancel:YES];
    imageVerifyAlert.sendImgCodeBlock = ^(BOOL isConfirm, NSString * _Nonnull code) {
        if (isConfirm) {
            [self requestLogin:code];
        } else {
            [[GlobalPopUpTool sharedInstance] removePopUpView];
        }
    };
}

- (IBAction)showOrHiddenPsdEvent:(UIButton *)sender {
    if (sender.selected) {
        [sender setImage:image(@"gcy_icon_close_eye") forState:UIControlStateNormal];
        _passwordTextField.secureTextEntry = YES;
       
    } else {
        [sender setImage:image(@"gcy_icon_open_eye") forState:UIControlStateNormal];
         _passwordTextField.secureTextEntry = NO;
    }
    sender.selected = !sender.selected;
}

/// 请求登录接口
/// @param phoneCode 图片验证码
- (void)requestLogin:(NSString *)phoneCode {
    
//    NSString *timeStamp = [DCSpeedy getCurrentTimesString];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *timeStamp = [formatter stringFromDate:[NSDate date]];

    NSMutableDictionary *dicParams = @{
        @"versionCode": @"1",
        @"branchCode": [UserDefaultUtil valueForKey:BranchCode],
        @"username":_telTextField.text,
        @"password":[DCSpeedy base64:CJStringWithFormat(@"%@_arpa_%@",_passwordTextField.text,timeStamp)],
        @"login_type":@"DRIVER",
        @"device_id":[DCSpeedy getUUID],
        @"response_type":@"token",
        @"grant_type":@"password",
        @"client_secret":@"e9d0139b041b11ea97dffa163e9d2a18",
        @"client_id":@"3dd160ba0f4111e18a97dffa163e9ios",
        @"time":timeStamp
    }.mutableCopy;
    
    if (![DCSpeedy isBlankString:phoneCode]) {
        [dicParams setValue:phoneCode forKey:@"phoneCode"];
    }
    
    WEAKSELF
    [HTTPManager postNetworkRequest:[NSString stringWithFormat:@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], @"/authorize"] withParameter:dicParams withVC:self netName:@"登录" success:^(id response, NSString *msg) {
        
        // 存储phone
        [UserDefaultUtil saveValue:response[@"party"][@"phone"] forKey:USER_PHONE];
        //存储token
        [UserDefaultUtil saveValue:response[@"access_token"] forKey:USER_TOKEN];
        //存储司机身份 0独立司机 1车队 2车队司机
        [UserDefaultUtil saveValue:response[@"driverType"] forKey:DRIVER_TYPE];
        [UserDefaultUtil saveValue:_passwordTextField.text forKey:USER_PASSWORD];
        //是否开启金昌saas功能
        [UserDefaultUtil saveValue:response[@"branch"][@"partyGroupConfigCacheMap"][@"needDriverLicense_needDriverLicense"][@"configValue"] forKey:isOpenJCSaasModule];
        //存储官网地址
        [UserDefaultUtil saveValue:response[@"branch"][@"wwwUrl"] forKey:WEBSITE];
        [UserDefaultUtil saveValue:response[@"branch"][@"mobilePhone"] forKey:CustomerTel];
        //司机code
        [UserDefaultUtil saveValue:response[@"party"][@"code"] forKey:USER_CODE];
        //极光 别名 注册（使用用户code注册）
        [JPUSHService setAlias: response[@"party"][@"code"] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            DebugLog(@"注册了极光别名推送：注册码：%tu,  别名是：%@,  请求序列号：%tu",iResCode,iAlias,seq);
        } seq:0];
        //极光 标签 注册 (使用网点code注册)
        NSSet *sets = [NSSet setWithObject:response[@"branch"][@"code"]];
        [JPUSHService setTags: sets completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
            DebugLog(@"注册了极光标签推送：注册码：%tu,  标签是：%@,  请求序列号：%tu",iResCode,iTags,seq);
        } seq:1];
        [KNotificationCenter postNotificationName:LOGIN_SUCCESS object:response];
        
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
            [self dismissViewControllerAnimated:YES completion:nil];
        });        
  
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (IBAction)buttonTypeClick:(UIButton *)sender {
    
    if (sender.tag == 100) {
        
        if (!self.isAgreeButton.isSelected) {
            NSString *agreementStr = [NSString stringWithFormat:@"请阅读并同意《%@司机端隐私政策》", APP_PlatformName];
            [XSInfoView showInfo:agreementStr onView:self.view];
            return;
        }
        
        if (_telTextField.text.length != 11) {
            [XSInfoView showInfo:@"手机号必须是11位" onView:self.view];
            return;
        }
        if (_passwordTextField.text.length > 20) {
            [XSInfoView showInfo:@"密码最长为20位" onView:self.view];
            return;
        }
        
        [self.view endEditing:YES];
                
        //登录
        if ([DCSpeedy isBlankString:_telTextField.text] == NO && [DCSpeedy isBlankString:_passwordTextField.text] == NO) {
            
            NSMutableDictionary *dicParams = @{
                @"username":_telTextField.text,
                @"branchCode": [UserDefaultUtil valueForKey:BranchCode]
            }.mutableCopy;

            WEAKSELF
            [HTTPManager getNetworkRequest:[NSString stringWithFormat:@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], @"/authorize/imageVerify"] withParameter:dicParams withVC:self netName:@"是否需要验证码" success:^(id response, NSString *msg) {
                NSString *needImage = [response objectForKey:@"needImage"];

                if ([needImage integerValue] == 1) { // 需要验证码
                    [weakSelf imgaeVerification];
                } else {
                    [weakSelf requestLogin:nil];
                }
            } failure:^(NSInteger code, NSString *msg) {

            }];
            
            
        }else{
            [XSInfoView showInfo:@"账号或密码为空~" onView:self.view];
        }
        
    }else if (sender.tag == 101) {
        //立即注册
        RegisterViewController *gvc = [[RegisterViewController alloc] init];
        [self.navigationController pushViewController:gvc animated:YES];
        
    }else {
        //忘记密码
        ForgetPasswordViewController *fpvc = [[ForgetPasswordViewController alloc] init];
        [self.navigationController pushViewController:fpvc animated:YES];
    }
}

- (void)theCountdown{
    
    UIButton *button = [self.view viewWithTag:102];
    
    __block int timeout= 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(timeout<=0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置界面的按钮显示 根据自己需求设置
                
                [button setTitle:@"获取验证码" forState:UIControlStateNormal];
                [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//                [button setBackgroundColor:[UIColor cy_colorWithHexString:@"#FE3905"]];
                button.userInteractionEnabled = YES;
            });
            
        }else{
            
            //            int minutes = timeout / 60;
            
            int seconds = timeout % 60;
            
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置界面的按钮显示 根据自己需求设置
                
                [UIView beginAnimations:nil context:nil];
                
                [UIView setAnimationDuration:0];
                
                [button setTitle:[NSString stringWithFormat:@"%@ S",strTime] forState:UIControlStateNormal];
                
                [UIView commitAnimations];
                
                button.userInteractionEnabled = NO;
                
            });
            
            timeout--;
            
        }
        
    });
    
    dispatch_resume(_timer);
}

- (IBAction)isAgreeButtonClick:(UIButton *)sender {
    sender.selected = !sender.selected;
}
- (IBAction)agreementTwoButtonAction:(UIButton *)sender {
    CYWebViewViewController *webVC = [[CYWebViewViewController alloc] init];
    webVC.titleString = @"税务发票代办委托书";
    webVC.urlString = CJStringWithFormat(@"%@/taxation.html", BasicDomainURL);
    webVC.state = 1;
    [self.navigationController pushViewController:webVC animated:YES];
}

- (IBAction)agreementButtonClick:(id)sender {
    CYWebViewViewController *webVC = [[CYWebViewViewController alloc] init];
    webVC.titleString = @"隐私协议";
    webVC.urlString = CJStringWithFormat(@"%@/agreement/agreement.html?agreementType=1", BasicDomainURL);
    webVC.state = 1;
    [self.navigationController pushViewController:webVC animated:YES];
}
- (IBAction)changeCodeLoginAction:(UIButton *)sender {
    LoginCodeViewController *vc = [[LoginCodeViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)dismissClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
